﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: BinWithEqualFrequency.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace BOL.Linq.Transformation
{
    public static partial class Binning
    {
        /// <summary>
        /// Groups the elements of a sequence into k interval of equal frequency. 
        /// </summary>
        /// <param name="source">The type of the elements of source.</param>
        /// <param name="k">The bin size.</param>
        /// <returns></returns>
        public static IEnumerable<IGrouping<double, double>> BinWithEqualFrequency(this IEnumerable<double> source, int k)
        {
            var list = source.ToList();
            var length = list.Count;
            var sortedList = list.OrderBy(x => x).ToList();
            var n = length / (double)k;
            var keys = Enumerable.Range(1, k).Select(i => i * n);

            return sortedList.Select((item, index) => new { item, index }).GroupBy(x => keys.FirstOrDefault(key => key > x.index), x => x.item);
        }

        /// <summary>
        /// Groups the elements of a sequence into k interval of equal frequency. 
        /// </summary>
        /// <param name="source">The type of the elements of source.</param>
        /// <param name="method">The method to determin bin size.</param>
        /// <returns></returns>
        public static IEnumerable<IGrouping<double, double>> BinWithEqualFrequency(this IEnumerable<double> source, BinSizeMethod method)
        {
            var list = source.ToList();

            return list.BinWithEqualFrequency(GetBinSize(list, method));
        }
    }
}
